package allen.ui.log;

import javax.swing.RowFilter;
import javax.swing.table.TableRowSorter;

import allen.log.LogDataCenter;
import allen.log.LogEntity;
import allen.log.LogLevel;

/**
 * Log entity filter.
 * */
class LogEntityFilter extends RowFilter<LogDataCenter, Integer> {
	/**
	 * Construct filter and add to sorter.
	 * */
	public static LogEntityFilter createFilterAndAddToSorter(
			TableRowSorter<LogDataCenter> sorter) {
		LogEntityFilter logEntityFilter = new LogEntityFilter(sorter);
		sorter.setRowFilter(logEntityFilter);
		return logEntityFilter;
	}

	/**
	 * Use this tag to filter all log entity.
	 * */
	public static final String AllLogNameTag = "All";

	private TableRowSorter<LogDataCenter> sorter;
	private LogNameFilter logNameFilter;
	private LogLevelFilter logLevelFilter;

	private LogEntityFilter(TableRowSorter<LogDataCenter> sorter) {
		this.sorter = sorter;
		logNameFilter = new LogNameFilter(AllLogNameTag);
		logLevelFilter = new LogLevelFilter(LogLevel.Trace);
	}

	void setLogName(String logName) {
		logNameFilter = new LogNameFilter(logName);
		this.sorter.setRowFilter(this);
	}

	void setLogLevel(LogLevel level) {
		logLevelFilter = new LogLevelFilter(level);
		this.sorter.setRowFilter(this);
	}

	@Override
	public boolean include(
			javax.swing.RowFilter.Entry<? extends LogDataCenter, ? extends Integer> entry) {
		return logNameFilter.include(entry) && logLevelFilter.include(entry);
	}
}

/**
 * Log name filter.
 * */
class LogNameFilter extends RowFilter<LogDataCenter, Integer> {

	private String name;

	LogNameFilter(String name) {
		this.name = name;
	}

	@Override
	public boolean include(
			javax.swing.RowFilter.Entry<? extends LogDataCenter, ? extends Integer> entry) {

		if (name.equals(LogEntityFilter.AllLogNameTag)) {
			return true;
		}

		LogEntity logEntity = entry.getModel().getLogEntity(
				entry.getIdentifier());
		return logEntity.getLogName().equals(name);
	}

}

/**
 * Log level Filter
 * */
class LogLevelFilter extends RowFilter<LogDataCenter, Integer> {
	private LogLevel level;

	LogLevelFilter(LogLevel level) {
		this.level = level;
	}

	@Override
	public boolean include(
			javax.swing.RowFilter.Entry<? extends LogDataCenter, ? extends Integer> entry) {
		LogEntity logEntity = entry.getModel().getLogEntity(
				entry.getIdentifier());
		return !logEntity.getLevel().isBelow(level);
	}
}
